<template>
  <div class="hv-dashboard-designer">
    <hv-designer-component-panel class="hv-designer-component-panel" />
    <div class="hv-dashboard-designer-main">
      <hv-designer-header-panel
        class="hv-dashboard-designer-header"
        v-model:dashboardTheme="dashboardTheme"
        :dashboardThemeList="dashboardThemeList"
        @save="save(undefined, true)"
        @back="back(true)"
        @preview="preview()"
        @saveAndBack="saveAndBack()"
        @dashboardThemeChange="dashboardThemeChange($event)"
        @reductionLog="reductionLog($event)"
      />
      <hv-designer-canvas-panel
        class="hv-designer-canvas-panel"
        :canvasData="canvasData"
        :componentData="componentData"
      />
    </div>
    <div class="hv-designer-config-panel">
      <a-tabs :size="'small'" v-model:activeKey="configPanelTabActiveKey">
        <a-tab-pane key="layerPanel">
          <template #tab>
            <hv-dynamic-icon iconName="SvgIconLayer" />
            图层
          </template>
          <hv-designer-layer-panel :layerData="layerData" />
        </a-tab-pane>
        <a-tab-pane key="pagePanel">
          <template #tab>
            <hv-dynamic-icon iconName="SvgIconPage" />
            画布属性
          </template>
          <hv-designer-canvas-prop-panel
            :canvasData="canvasData"
            v-model:dashboardCategoryId="dashboardCategoryId"
            :resolutionRatioList="resolutionRatioList"
            :categoryList="dashboardCategoryList"
          />
        </a-tab-pane>
        <a-tab-pane key="propPanel">
          <template #tab>
            <hv-dynamic-icon iconName="SvgIconProperty" />
            组件属性
          </template>
          <hv-designer-component-prop-panel />
        </a-tab-pane>
      </a-tabs>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, onUnmounted, ref } from "vue";
import DesignerHeaderPanel from "../../components/dashboard/designer/DesignerHeaderPanel.vue";
import DesignerComponentPanel from "../../components/dashboard/designer/DesignerComponentPanel.vue";
import DesignerCanvasPanel from "../../components/dashboard/designer/DesignerCanvasPanel.vue";
import DesignerLayerPanel from "../../components/dashboard/designer/DesignerLayerPanel.vue";
import DesignerComponentPropPanel from "../../components/dashboard/designer/DesignerComponentPropPanel.vue";
import DesignerCanvasPropPanel from "../../components/dashboard/designer/DesignerCanvasPropPanel.vue";

import {
  canvasInitOptions,
  canvasPanelConfig,
  layerPanelConfig,
  resolutionRatioList,
} from "@/visual/configs/dashboard-conifg";
import { cloneDeep } from "lodash";

import { useRouter, useRoute } from "vue-router";
import { notification } from "ant-design-vue";
import type DashboardCanvasType from "@/visual/commons/types/dashboard-canvas-type";
import CommonUtil from "@/visual/commons/utils/common-util";
import type DashboardComponentType from "@/visual/commons/types/dashboard-component-type";
import DashboardEvent from "@/visual/events/dashboard-event";
import DashboardApi from "@/visual/apis/dashboard-api";
import HttpResultUtil from "@/visual/commons/utils/http-result-util";
import { useDashboardStore } from "@/visual/stores/dashboard";
import { useVisualConfigStore } from "@/visual/stores/visual-config";
import type DashboardCategoryType from "@/visual/commons/types/dashboard-category-type";
import type DashboardLogType from "@/visual/commons/types/dashboard-log-type";
import { useSpinningStore } from "@/visual/stores/spinning";
import useConfirm from "@/visual/hooks/use-confirm";

export default defineComponent({
  name: "DashboardAdd",
  components: {
    hvDesignerHeaderPanel: DesignerHeaderPanel,
    hvDesignerComponentPanel: DesignerComponentPanel,
    hvDesignerCanvasPanel: DesignerCanvasPanel,
    hvDesignerLayerPanel: DesignerLayerPanel,
    hvDesignerComponentPropPanel: DesignerComponentPropPanel,
    hvDesignerCanvasPropPanel: DesignerCanvasPropPanel,
  },
  setup() {
    const router = useRouter();
    const route = useRoute();
    const useDashboard = useDashboardStore();
    const useVisualConfig = useVisualConfigStore();
    const useSpinning = useSpinningStore();

    const configPanelTabActiveKey = ref<string>("layerPanel");
    const dashboardThemeList = ref<any>([]);
    const dashboardCategoryList = ref<DashboardCategoryType[]>([]);

    const dashboardRoot = useVisualConfig.getRoutePath.dashboardRoot;
    const visualRoot = useVisualConfig.getRoutePath.visualRoot;

    //主题
    const dashboardTheme = ref<string>("");

    //仪表板类别
    const dashboardCategoryId = ref<string>("");

    //画布数据
    const canvasData = ref<DashboardCanvasType>({
      ...cloneDeep(canvasInitOptions),
      id: CommonUtil.shortUUID(),
      label: "未命名" + CommonUtil.shortUUID(),
    });

    //图层数据
    const layerData: any = ref([cloneDeep(layerPanelConfig.layerTreeRootNode)]);

    //组件数据
    const componentData = ref<DashboardComponentType<any>[]>([
      cloneDeep(canvasPanelConfig.componentTreeRootNode),
    ]);

    /**
     * 初始化
     */
    const init = () => {
      useDashboard.setDashboardTempId("temp" + CommonUtil.UUID32());
      // 切换tabs
      DashboardEvent.getConfigPanelTabTaggleEvent().subscribe((data: any) => {
        configPanelTabActiveKey.value = data.name;
        data.success && data.success();
      });
    };

    /**
     * 初始化数据
     */
    const initData = () => {
      const dashboardId = route.query.id;
      useSpinning.setSpinningVisible(true);
      DashboardApi.initDashboardAddData(dashboardId ? dashboardId + "" : "").then(
        (res) => {
          useSpinning.setSpinningVisible(false);
          if (HttpResultUtil.isSuccess(res)) {
            if (
              res.data.responseData &&
              res.data.responseData.dashboardThemeList &&
              res.data.responseData.dashboardThemeList.length
            ) {
              dashboardThemeList.value = res.data.responseData.dashboardThemeList;
            } else {
              dashboardThemeList.value = [];
            }

            if (
              res.data.responseData &&
              res.data.responseData.dashboardCategoryList &&
              res.data.responseData.dashboardCategoryList.length
            ) {
              dashboardCategoryList.value = res.data.responseData.dashboardCategoryList;
            } else {
              dashboardCategoryList.value = [];
            }

            if (res.data.responseData.dashboardData) {
              res.data.responseData.dashboardData.canvasData &&
                (canvasData.value = JSON.parse(
                  res.data.responseData.dashboardData.canvasData
                ));
              res.data.responseData.dashboardData.layerData &&
                (layerData.value = JSON.parse(
                  res.data.responseData.dashboardData.layerData
                ));
              res.data.responseData.dashboardData.componentData &&
                (componentData.value = JSON.parse(
                  res.data.responseData.dashboardData.componentData
                ));

              if (res.data.responseData.dashboardData.themeId) {
                dashboardTheme.value = res.data.responseData.dashboardData.themeId;
              } else {
                dashboardTheme.value =
                  dashboardThemeList.value && dashboardThemeList.value.length > 0
                    ? dashboardThemeList.value[0].themeId
                    : "";
              }

              if (res.data.responseData.dashboardData.dashboardCategoryId) {
                dashboardCategoryId.value =
                  res.data.responseData.dashboardData.dashboardCategoryId;
              } else {
                dashboardCategoryId.value =
                  dashboardCategoryList.value &&
                  dashboardCategoryList.value.length > 0 &&
                  dashboardCategoryList.value[0].dashboardCategoryId
                    ? dashboardCategoryList.value[0].dashboardCategoryId
                    : "";
              }
            } else {
              dashboardTheme.value =
                dashboardThemeList.value && dashboardThemeList.value.length > 0
                  ? dashboardThemeList.value[0].themeId
                  : "";

              dashboardCategoryId.value =
                dashboardCategoryList.value &&
                dashboardCategoryList.value.length > 0 &&
                dashboardCategoryList.value[0].dashboardCategoryId
                  ? dashboardCategoryList.value[0].dashboardCategoryId
                  : "";
            }
          } else {
            HttpResultUtil.failureTipMsg(res);
          }
        },
        () => {
          useSpinning.setSpinningVisible(false);
        }
      );
    };

    /**
     * 保存
     */
    const save = (cb: Function | undefined, showMsg: boolean) => {
      const dashboardData = {
        dashboardId: route.query.id,
        dashboardTempId: useDashboard.getDashboardTempId,
        dashboardTitle: canvasData.value.label,
        layerData: JSON.stringify(layerData.value),
        componentData: JSON.stringify(componentData.value),
        canvasData: JSON.stringify(canvasData.value),
        themeId: dashboardTheme.value,
        dashboardCategoryId: dashboardCategoryId.value,
        createUser: useVisualConfig.getUserInfo.userName,
        createUserId: useVisualConfig.getUserInfo.userId,
      };

      console.log(dashboardData);
      useSpinning.setSpinningVisible(true);
      DashboardApi.saveDashboard(dashboardData).then(
        (res) => {
          useSpinning.setSpinningVisible(false);
          if (HttpResultUtil.isSuccess(res)) {
            showMsg &&
              notification.success({
                message: "提示",
                description: res.data.msg,
              });

            if (cb) {
              cb(false);
            } else {
              if (!route.query.id) {
                router.push({
                  path: dashboardRoot + "/dashboardEdit",
                  query: {
                    id: res.data.responseData.dashboardId,
                  },
                });
              }
            }
          } else {
            HttpResultUtil.failureTipMsg(res);
          }
        },
        () => {
          useSpinning.setSpinningVisible(false);
        }
      );
    };

    /**
     * 返回
     */
    const back = (confirm: boolean) => {
      const backRouter = () => {
        router.push({ path: visualRoot + "/dashboardList" });
      };
      if (confirm) {
        useConfirm({
          wrapClassName: "hv-dark-confirm",
          title: "确认",
          content: "数据可能未保存，您确认要返回吗？",
          onOk() {
            backRouter();
          },
        });
      } else {
        backRouter();
      }
    };

    /**
     * 保存并返回
     */
    const saveAndBack = () => {
      save(back, true);
    };

    /**
     * 预览
     */
    const preview = () => {};

    /**
     * 主题改变
     * @param val
     */
    const dashboardThemeChange = (themeConfig: any) => {
      useDashboard.setDashboardThemeConfig(themeConfig);
    };

    /**
     * 还原日志
     * @param log
     */
    const reductionLog = (log: DashboardLogType) => {
      console.info(log);
      dashboardTheme.value = log.themeId;
      useDashboard.setDashboardThemeConfig(cloneDeep(log.dashboardTheme.themeConfig));
      canvasData.value = JSON.parse(cloneDeep(log.canvasData));
      layerData.value = JSON.parse(cloneDeep(log.layerData));
      componentData.value = JSON.parse(cloneDeep(log.componentData));
      dashboardCategoryId.value = log.dashboardCategoryId;
      configPanelTabActiveKey.value = "layerPanel";
      //清空当前组件属性配置
      DashboardEvent.getConfigPanelCurrentPropEvent().next({
        undefined,
      });
    };

    onMounted(() => {
      initData();
      init();
    });

    onUnmounted(() => {
      //关闭事件
      DashboardEvent.removeAll();
    });

    return {
      dashboardCategoryId,
      canvasData,
      layerData,
      componentData,
      configPanelTabActiveKey,
      resolutionRatioList,
      dashboardCategoryList,
      dashboardThemeList,
      dashboardTheme,
      save,
      preview,
      back,
      saveAndBack,
      dashboardThemeChange,
      reductionLog,
    };
  },
});
</script>

<style lang="less" scoped>
@import "./DashboardAdd.less";
</style>
